package com.settlement.system.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.CommonPlugIn;
import com.settlement.system.model.entity.common.TblWpRateConfig;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.IBrandService;
import com.settlement.system.service.ITblWpRateConfigService;
import com.settlement.system.service.IWpPlugInService;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.model.vo.TreeJson;
import com.alibaba.excel.context.AnalysisContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 唯品会比例设置 前端控制器
 * @author Ximi
 * @since 2020-04-15
 */

@RestController
@Slf4j
@RequestMapping("/wp/rateConfig")
public class TblWpRateConfigController extends ExcelController<TblWpRateConfig>  {

    @Resource
    private ITblWpRateConfigService tblWpRateConfigService;

    @Resource
    private IBrandService brandService;

    @Resource
    private IWpPlugInService wpPlugInService;

    @Override
    public IBaseService init() {
        return tblWpRateConfigService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblWpRateConfig.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        final String brandNoKey = "brandNo";
        if(model.containsKey(brandNoKey) && model.get(brandNoKey) != null){
            String brandNo = model.get(brandNoKey).toString();
            if(!StringUtils.isEmpty(brandNo)){
                model.put(brandNoKey, FasUtil.formatInQueryCondition(brandNo));
            }
        }
        FasUtil.formatInQueryCondition(model, "retailCategoryNo");
        super.setParamsModel(model);
    }

    @Override
    public String verifyImportObject(TblWpRateConfig tblWpRateConfig, AnalysisContext analysisContext) {
        try {
            if(analysisContext.readSheetHolder().getSheetNo() != 0){
                return null;
            }

            if(StringUtils.isNotEmpty(tblWpRateConfig.getRetailCategoryName())){
                String categoryNoByName = getCategoryNoByName(tblWpRateConfig.getRetailCategoryName());
                if(StringUtils.isEmpty(categoryNoByName)){
                    return "零售大类不存在";
                }
                tblWpRateConfig.setRetailCategoryNo(categoryNoByName);
            }

            TblWpRateConfig temp = tblWpRateConfigService.selectSingleByModel(tblWpRateConfig);
            if(temp != null){
                return "数据重复";
            }

            if(StringUtils.isNotEmpty(tblWpRateConfig.getBrandNo()) && StringUtils.isEmpty(tblWpRateConfig.getBrandName())){
                setModelValue(tblWpRateConfig);
            }

        } catch (Exception e) {
            log.error("导入时错误",e);
            return "导入时错误";
        }
        return super.verifyImportObject(tblWpRateConfig, analysisContext);
    }

    private String getCategoryNoByName(String categoryName) throws ServiceException {
        List<CommonPlugIn> categoryList = wpPlugInService.searchCategoryList(null);
        for (CommonPlugIn commonPlugIn : categoryList) {
            if(commonPlugIn.getName().equals(categoryName)){
                return commonPlugIn.getNo();
            }
        }
        return null;
    }

    @Override
    protected void setModelValue(TblWpRateConfig model) throws Exception {
        if(StringUtils.isEmpty(model.getId())){
            String brandNo = model.getBrandNo();
            Map<String, Object> params = new HashMap<>();
            params.put("brandNo",brandNo);
            List<TreeJson> treeJsons = brandService.selectBrandWithBrandUnit(params);
            if(CollectionUtils.isNotEmpty(treeJsons)){
                TreeJson treeJson = treeJsons.get(0).getChildren().get(0);
                String text = treeJson.getText();
                model.setBrandName(text);
            }
        }
    }

    @Override
    protected ObjectDataResponse update(@RequestBody TblWpRateConfig model, HttpServletRequest request) {
        try {
            setModelValue(model);
            setDefualt(model);
            TblWpRateConfig tblWpRateConfig = tblWpRateConfigService.selectSingleByModel(model);
            if(tblWpRateConfig!=null && !tblWpRateConfig.getId().equals(model.getId())){
                return new ObjectDataResponse(500,"更新失败，数据已经存在");
            }
            tblWpRateConfigService.update(model);
            return new ObjectDataResponse(200, "更新成功");
        } catch (Exception ex) {
            if(ex.getCause() != null &&
                    (ex.getCause() instanceof SQLIntegrityConstraintViolationException
                            || ex.getCause() instanceof DuplicateKeyException)){
                return new ObjectDataResponse(500,"更新失败，数据已经存在！");
            }else {
                log.error("保存异常",ex);
                return new ObjectDataResponse(500,"更新失败，请联系管理员！");
            }
        }
    }

    @Override
    protected ObjectDataResponse insert(@RequestBody TblWpRateConfig model, HttpServletRequest request) {
        try {
            setModelValue(model);
            setDefualt(model);
            TblWpRateConfig tblWpRateConfig = tblWpRateConfigService.selectSingleByModel(model);
            if(tblWpRateConfig!=null){
                return new ObjectDataResponse(500,"新增失败，数据已经存在！");
            }

            tblWpRateConfigService.insert(model);
            return new ObjectDataResponse(200,"新增成功");
        } catch (Exception ex){

            boolean flag = ex.getCause() != null &&
                    (ex.getCause() instanceof SQLIntegrityConstraintViolationException
                        || ex.getCause() instanceof DuplicateKeyException);
            if(flag){
                return new ObjectDataResponse(500,"新增失败，数据已经存在！");
            }else {
                log.error("保存异常",ex);
                return new ObjectDataResponse(500,"新增失败，请联系管理员！");
            }
        }
    }

    @Override
    protected String validateAllDate(List<TblWpRateConfig> datas, AnalysisContext analysisContext) {

        if(analysisContext.readSheetHolder().getSheetNo() != 0){
            return null;
        }

        List<String> list = new ArrayList<>();
        for (TblWpRateConfig data : datas) {
            String toString = data.toString();
            if (list.contains(toString)) {
                return "有两行数据重复";
            } else {
                list.add(toString);
            }
        }

        return super.validateAllDate(datas);
    }

    @Override
    protected void saveData(List<TblWpRateConfig> datas, AnalysisContext analysisContext) throws ServiceException {
        if(analysisContext.readSheetHolder().getSheetNo() != 0){
            return;
        }
        super.saveData(datas, analysisContext);
    }
}

